package com.base.schema.singleton;

/**
 * 懒汉式1 简单判断非空（多线程并发不安全，单线程无影响）
 * @ClassName: SingletonDemo3
 * @Description: 
 * @Author xuyou
 * @DateTime 2021年3月2日 上午10:59:43
 */
public class SingletonDemo3 {
  
	//1: 构造方法私有化,外部无法使用new构造方法创建对象
	private SingletonDemo3() {};
	
	//2: 内部创建对象
	private static SingletonDemo3 instence;
	
	//3: 提供一个对外获取实例的方法
	public static SingletonDemo3 getInstence() {
		if (instence == null) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			instence = new SingletonDemo3();
		}
		return instence;
	}
	
	public static void main(String[] args) {
		//单线程获取无影响
//		SingletonDemo3 instence1 = SingletonDemo3.getInstence();
//		SingletonDemo3 instence2 = SingletonDemo3.getInstence();
//		System.out.println(instence1 == instence2);
		
		//模拟线程不安全
		for (int i = 0; i < 10; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					SingletonDemo3 instence1 = SingletonDemo3.getInstence();	
					System.out.println(instence1);
				}
			}).start();
		}
		
	}
	
}
